import { CloseCircleOutlined } from '@ant-design/icons';
import { ModalForm, ProCard, ProDescriptions } from '@ant-design/pro-components';
import { ProFormDigit, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { Collapse, FormInstance, Image, message, Spin, Steps, Table, TableColumnsType } from 'antd';
import { useEffect, useRef, useState } from 'react';
import styles from '../index.less';
import { getOrderDetail, parkRefund } from '../service';
import { orderDetail } from '../types';
import { parkOrderTag } from './utilElement';

const { Panel } = Collapse;

interface addProps {
  close: (e: boolean) => void;
  id?: string;
}
const { Step } = Steps;
export default (props: addProps) => {
  const { close, id } = props;
  const formRef = useRef<FormInstance>();

  const [enterPlateVisible, setEnterPlateVisible] = useState(false);
  const [enterImageVisible, setEnterImageVisible] = useState(false);
  const [spinVisible, setSpinVisible] = useState(false);
  const [outPlateVisible, setOutPlateVisible] = useState(false);
  const [outImageVisible, setOutImageVisible] = useState(false);
  const [detailsItem, setDetailsItem] = useState<orderDetail>();
  const [refundVisible, setRefundVisible] = useState<boolean>(false);
  const [totalActualAmount, setTotalActualAmount] = useState<number>();
  const [payRecord, setPayRecord] = useState();
  const [refundId, setRefundId] = useState<string>();
  const carAttribute_MAP = new Map()
    .set(4, '临时车')
    .set(3, '无牌车')
    .set(2, '会员车')
    .set(1, '固定车');
  const carType_MAP = new Map()
    .set(4, '其他车辆')
    .set(3, '新能源车')
    .set(2, '大型车')
    .set(1, '小型车');
  const poayment_type = new Map()
    .set(20, '现金支付')
    .set(4, '支付宝支付')
    .set(3, '微信支付')
    .set(2, '支付宝H5')
    .set(1, '微信H5');

  const order_status = new Map([
    [0, '未结算'],
    [1, '未支付'],
    [2, '已结清'],
    [5, '已退款'],
    [6, '部分退款'],
    [7, '未结清'],
    [10, '免费'],
    [-1, ''],
  ]);

  const RefundStatus = new Map()
    .set(3, '退款失败')
    .set(2, '退款成功')
    .set(1, '退款申请中')
    .set(0, '');
  const channelType = new Map().set(3, '出口不收费').set(2, '出口收费').set(1, '入口').set(0, '');
  const passType = new Map().set(3, '遥控放行').set(2, '软件异常放行').set(1, '正常');
  useEffect(() => {
    setSpinVisible(true);

    getOrderDetail(id).then((res) => {
      if (res) {
        setDetailsItem(res.data);
        setPayRecord(res.data?.paymentOrders);
        setSpinVisible(false);
      }
    });
  }, [refundVisible]);

  const columns: TableColumnsType<any> | undefined[] = [
    {
      title: '支付记录编号',
      ellipsis: true,
      dataIndex: 'tradeNo',
    },
    {
      title: '支付方式',
      dataIndex: 'channelType',
      ellipsis: true,
      render: (_, record) => {
        if (record) return <div>{poayment_type.get(record.channelType)}</div>;
        return '-';
      },
    },
    {
      title: '支付金额',
      dataIndex: 'amountValue',
      ellipsis: true,
      render: (_, record) => {
        if (record) return <div>{Number(record.amountValue).toFixed(2)}</div>;
        return '-';
      },
    },
    {
      title: '支付状态',
      dataIndex: 'status',
      ellipsis: true,
      render: (_, record) => {
        if (record) {
          return <div>{order_status.get(record.status)}</div>;
        }
        return '-';
      },
    },
    {
      title: '发起时间',
      ellipsis: true,
      dataIndex: 'paymentDate',
      render: (_, record) => {
        if (record?.paymentDate) return <div>{record.paymentDate}</div>;
        return '-';
      },
    },
    {
      title: '支付时间 ',
      ellipsis: true,
      dataIndex: 'successDate',
      render: (_, record) => {
        if (record?.successDate) return <div>{record.successDate}</div>;
        return '-';
      },
    },
    {
      title: '退款单号',
      ellipsis: true,
      dataIndex: 'refundNo',
      render: (_, record) => {
        if (record?.refundNo) return <div>{record.refundNo}</div>;
        return '-';
      },
    },
    {
      title: '退款金额',
      dataIndex: 'appliedRefundAmount',
      ellipsis: true,
      render: (_, record) => {
        if (record?.appliedRefundAmount)
          return <div>{Number(record.appliedRefundAmount).toFixed(2)}</div>;
        return '-';
      },
    },
    {
      title: '退款状态',
      dataIndex: 'refundStatus',
      ellipsis: true,
      render: (_, record) => {
        if (record.refundStatus) return <div>{RefundStatus.get(record.refundStatus)}</div>;
        return '-';
      },
    },
    {
      fixed: 'right',
      title: '操作',
      ellipsis: true,
      render: (_, record) => {
        return (
          <>
            {record.refundStatus == 2 || record.refundStatus == 1 ? (
              <div>{record.refundStatus == 2 ? '已退款' : '退款中'}</div>
            ) : (
              <a
                onClick={() => {
                  setTotalActualAmount(Number(record.amountValue));
                  setRefundId(record.tradeNo);
                  setRefundVisible(true);
                }}
              >
                退款
              </a>
            )}
          </>
        );
      },
    },
  ];

  return (
    <Spin spinning={spinVisible}>
      {Boolean(detailsItem?.orderStatus) && detailsItem?.orderStatus !== 1 && (
        <ProCard
          title={
            <div style={{ fontWeight: 700, fontSize: 16 }}>
              <CloseCircleOutlined style={{ color: '#FF4D4F', marginRight: 10, fontSize: 20 }} />
              异常订单
            </div>
          }
          bordered
          style={{ borderColor: '#FF7875', marginBottom: 20, backgroundColor: '#FFF1F0' }}
        >
          <div style={{ marginLeft: 30 }}>异常原因:{detailsItem?.paymentStatusDesc}</div>
        </ProCard>
      )}
      <ProCard
        title={
          <div style={{ fontSize: 20, fontWeight: 700, alignItems: 'center', display: 'flex' }}>
            基本信息{' '}
            {detailsItem?.status == 2 && detailsItem?.orderStatus == 1 && parkOrderTag.loading}
            {(detailsItem?.status == 9 || detailsItem?.status == 10) &&
              detailsItem?.orderStatus == 1 &&
              parkOrderTag.success}
          </div>
        }
        className={styles.card}
        bordered={false}
        style={{ marginBottom: 20 }}
      >
        <ProDescriptions>
          <ProDescriptions.Item label="订单编号">{detailsItem?.orderNo}</ProDescriptions.Item>
          <ProDescriptions.Item label="停车场名称">{detailsItem?.zoneName}</ProDescriptions.Item>
          <ProDescriptions.Item label="支付状态">
            {order_status.get(detailsItem?.paymentStatus ?? -1)}
          </ProDescriptions.Item>
          <ProDescriptions.Item label="车牌号码">{detailsItem?.plateNumber}</ProDescriptions.Item>
          <ProDescriptions.Item label="车辆类型">
            {carType_MAP.get(detailsItem?.carType)}
          </ProDescriptions.Item>
          <ProDescriptions.Item label="应收金额">
            {detailsItem?.totalAmount ? Number(detailsItem?.totalAmount).toFixed(2) : '0.00'}
          </ProDescriptions.Item>
          <ProDescriptions.Item label="车辆颜色">{detailsItem?.plateColor}</ProDescriptions.Item>
          <ProDescriptions.Item label="车辆属性">
            {carAttribute_MAP.get(detailsItem?.carAttributes)}
          </ProDescriptions.Item>
          <ProDescriptions.Item label="实收金额">
            {detailsItem?.totalActualAmount
              ? Number(detailsItem?.totalActualAmount).toFixed(2)
              : '0.00'}
          </ProDescriptions.Item>
          <ProDescriptions.Item label="车牌图片">
            {detailsItem?.inAccessRecord?.plateImageUrl && (
              <Image
                style={{ marginBottom: 7 }}
                height={20}
                src={detailsItem?.inAccessRecord?.plateImageUrl}
              />
            )}
          </ProDescriptions.Item>
          <ProDescriptions.Item label="停车时长">{detailsItem?.durationTime}</ProDescriptions.Item>
          <ProDescriptions.Item label="待收金额">
            {detailsItem?.reductionAmount
              ? Number(detailsItem?.reductionAmount).toFixed(2)
              : '0.00'}
          </ProDescriptions.Item>
        </ProDescriptions>
      </ProCard>
      <ProCard
        title={<div style={{ fontSize: 20, fontWeight: 700 }}>订单流程</div>}
        className={styles.card}
        bordered={false}
        style={{ paddingRight: 65, marginBottom: 20 }}
      >
        <Steps current={detailsItem?.orderStatus} percent={60}>
          {[...Array(detailsItem?.processRecords.length)].map((_, index) => (
            <Step
              key={`step${index}`}
              title={detailsItem?.processRecords[index]?.name}
              description={detailsItem?.processRecords[index]?.description}
              subTitle={detailsItem?.processRecords[index]?.operationTime}
            />
          ))}
        </Steps>
      </ProCard>
      <ProCard
        title={<div style={{ fontSize: 20, fontWeight: 700 }}>出入场信息</div>}
        className={styles.card}
        bordered={false}
        style={{ paddingRight: 65, marginBottom: 20 }}
      >
        <ProCard
          title={<div style={{ fontSize: 16, fontWeight: 700 }}>入场信息</div>}
          bordered
          type="inner"
          style={{ marginLeft: 8 }}
        >
          <ProDescriptions column={2}>
            <ProDescriptions.Item label="通道类型">
              {channelType.get(detailsItem?.inAccessRecord?.channelType)}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="放行方式">
              {passType.get(detailsItem?.inAccessRecord?.releaseMode)}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="通道名称">
              {detailsItem?.inAccessRecord?.channelName}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="过车车牌">
              {detailsItem?.inAccessRecord?.plateImageUrl && (
                <>
                  <a onClick={() => setEnterPlateVisible(true)}>查看车牌</a>
                  <Image
                    width={200}
                    style={{ display: 'none' }}
                    preview={{
                      visible: enterPlateVisible,
                      src: detailsItem?.inAccessRecord?.plateImageUrl,
                      onVisibleChange: (value) => {
                        setEnterPlateVisible(value);
                      },
                    }}
                  />
                </>
              )}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="过车时间">
              {detailsItem?.inAccessRecord?.passTime}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="过车图片">
              {detailsItem?.inAccessRecord?.passImageUrl && (
                <>
                  <a onClick={() => setEnterImageVisible(true)}>查看图片</a>
                  <Image
                    width={200}
                    style={{ display: 'none' }}
                    preview={{
                      visible: enterImageVisible,
                      src: detailsItem?.inAccessRecord?.passImageUrl,
                      onVisibleChange: (value) => {
                        setEnterImageVisible(value);
                      },
                    }}
                  />
                </>
              )}
            </ProDescriptions.Item>
          </ProDescriptions>
        </ProCard>
        <ProCard
          title={<div style={{ fontSize: 16, fontWeight: 700 }}>出场信息</div>}
          bordered
          type="inner"
          style={{ marginLeft: 30 }}
        >
          <ProDescriptions column={2}>
            <ProDescriptions.Item label="通道类型">
              {channelType.get(detailsItem?.outAccessRecord?.channelType ?? 0)}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="放行方式">
              {passType.get(detailsItem?.outAccessRecord?.releaseMode)}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="通道名称">
              {detailsItem?.outAccessRecord?.channelName ?? ''}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="过车车牌">
              {detailsItem?.outAccessRecord?.plateImageUrl && (
                <>
                  <a onClick={() => setOutPlateVisible(true)}>查看车牌</a>
                  <Image
                    width={200}
                    style={{ display: 'none' }}
                    preview={{
                      visible: outPlateVisible,
                      src: detailsItem?.outAccessRecord?.plateImageUrl,
                      onVisibleChange: (value) => {
                        setOutPlateVisible(value);
                      },
                    }}
                  />
                </>
              )}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="过车时间">
              {detailsItem?.outAccessRecord?.passTime}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="过车图片">
              {detailsItem?.outAccessRecord?.passImageUrl && (
                <>
                  <a onClick={() => setOutImageVisible(true)}>查看图片</a>
                  <Image
                    width={200}
                    style={{ display: 'none' }}
                    preview={{
                      visible: outImageVisible,
                      src: detailsItem?.outAccessRecord?.passImageUrl,
                      onVisibleChange: (value) => {
                        setOutImageVisible(value);
                      },
                    }}
                  />
                </>
              )}
            </ProDescriptions.Item>
          </ProDescriptions>
        </ProCard>
      </ProCard>
      <ProCard
        title={<div style={{ fontSize: 20, fontWeight: 700 }}>支付记录</div>}
        className={styles.card}
        bordered={false}
        style={{ marginBottom: 20 }}
      >
        <Table columns={columns} dataSource={payRecord} scroll={{ x: true }} />
      </ProCard>
      {/* <FooterToolbar key="addFooterBar">
        <Button
          type="primary"
          key="submit"
          onClick={() => {
            setRefundVisible(true);
          }}
        >
          退款
        </Button>
      </FooterToolbar> */}
      <ModalForm
        layout="horizontal"
        width={650}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        onFinish={async (values) => {
          const value = {
            ...values,
            tradeNo: refundId,
          };
          const res: any = await parkRefund(value);
          if (res && res.code == 0) {
            message.success('退款成功');
            setRefundVisible(false);
            return true;
          }
          message.error('退款失败 ' + res.message);
          return false;
        }}
        open={refundVisible}
        title="退款申请"
        formRef={formRef}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setRefundVisible(false);
          },
          centered: true,
          footer: null,
        }}
      >
        <ProFormText
          label="订单编号"
          disabled
          required={true}
          name="orderNo"
          initialValue={detailsItem?.orderNo}
        />
        {/* <ProFormText
          label="退款记录"
          disabled
          required={true}
          name="record"
          initialValue={'接口还没写完'}
        /> */}
        <ProFormDigit
          label="退款金额"
          disabled
          name="refundAmount"
          rules={[{ required: true, message: '退款金额不能为空' }]}
          placeholder={'请输入退款金额'}
          min={0}
          initialValue={totalActualAmount}
        />
        {/* <ProFormText
          label="退款用户"
          placeholder={'请填写退款用户信息(如手机号)'}
          name={'refundUserPhone'}
        /> */}
        <ProFormTextArea label="退款原因" placeholder={'请填写退款原因'} name={'refundReason'} />
      </ModalForm>
    </Spin>
  );
};
